/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

/**
 *
 * @author pc0129
 */
import java.io.*;
import java.net.*;
import java.util.*;

public class Client {

    static Socket kkSocket = null;
    static PrintWriter out = null;
    static BufferedReader in = null;
    static String address = null;
    String fromUser;
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    String fromServer;
    FactorFinder f = new FactorFinder();
    int error = 0;

    public static void main(String[] args) throws IOException{
        Client c = new Client();
        while (true) {
            c.createSocket();
            c.communicationsHandler();
        }
    }
    public static void start() throws IOException {
        Client c = new Client();
        while (true) {
            c.createSocket();
            c.communicationsHandler();
        }
    }
    public void createSocket() {
        
        
        try {
            kkSocket = new Socket("168.18.145.132", 4444);
            address = Client.kkSocket.getLocalAddress().toString();
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            error = 0;
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: L203C18.cs.tamu.edu");
            //System.exit(1);
            error = 1;
        } catch (IOException e) {
            System.err.println(e.getMessage());
            error = 1;
        }
    }

    public synchronized void communicationsHandler() throws IOException {
        //System.err.println("communicationsHandler()");
        if (error == 1) {

            kkSocket = null;
            out = null;
            in = null;
            fromUser = null;
            stdIn = new BufferedReader(new InputStreamReader(System.in));
            fromServer = null;
            f = new FactorFinder();
            try{out.close();
            in.close();
            stdIn.close();
            kkSocket.close();}
            catch (Exception e){}
            return;
        }
        try {
            while ((fromServer = in.readLine()) != null) {
                if (fromServer.equals("STOP")) {
                    break;
                }
                f.factorProcess(fromServer);
                String outputFactorFinder = f.getArrayList();
                System.out.println("ArrayList: " + outputFactorFinder);
                out.println(outputFactorFinder);
               

            }

            out.close();
            in.close();
            stdIn.close();
            kkSocket.close();
        } catch (Exception e) {
            return;
        }
    }

}
